package com.hzdl.car.controller;

import com.github.pagehelper.PageInfo;
import com.hzdl.car.bean.Announce;
import com.hzdl.car.bean.User;
import com.hzdl.car.service.AnnounceService;
import com.hzdl.car.util.AJAXResult;
import com.hzdl.car.vo.AnnounceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/annouce")
public class AnnounceController {
    @Autowired
    private AnnounceService as;

    @RequestMapping("/annouceInit")
    public String annouceInit(){
        return "/system/announce";
    }
    @RequestMapping("/announceShow")
    @ResponseBody
    public AJAXResult annouceShow(AnnounceVo annouceVo){
        if(annouceVo.getPage()==null){
            annouceVo.setPage(1);
        }
        if(annouceVo.getLimit()==null){
            annouceVo.setLimit(5);
        }
        PageInfo pageInfo=as.findAnnouncebyWhere(annouceVo);
        return new AJAXResult(0,"",pageInfo.getList(),pageInfo.getTotal());
    }
    @RequestMapping("/newsAdd")
    @ResponseBody
    public AJAXResult newAdd(AnnounceVo annouceVo, HttpSession session){
        User user=(User)session.getAttribute("user");
        if(annouceVo.getPublishername()==null||annouceVo.getPublishername().isEmpty()){
            annouceVo.setPublishername(user.getRealname());
        }
        if(annouceVo.getId()==null){
           int row=as.insertNews(annouceVo);
           if(row==0){
               return AJAXResult.ADD_ERROR;
           }
           return AJAXResult.ADD_SUCCESS;
        }else {
            int row1=as.updateNews(annouceVo);
            if(row1==0){
                return AJAXResult.UPDATE_ERROR;
            }
            return AJAXResult.UPDATE_SUCCESS;
        }
    }
    @RequestMapping("/newsDelete")
    @ResponseBody
    public AJAXResult newsDelete(String newsId){
        int row=as.deleteNewsById(Integer.valueOf(newsId));
        if(row==0){
          return AJAXResult.DELETE_ERROR;
        }
        return AJAXResult.DELETE_SUCCESS;
    }
    @RequestMapping("/deleteAllNews")
    @ResponseBody
    public AJAXResult deleteAllNews(String ids){
        String[] id = ids.split(",");
        int row=0;
        for(int i=0;i<id.length;i++){
            row+=as.deleteNewsById(Integer.valueOf(id[i]));
        }
        if(row==0){
            return AJAXResult.DELETE_ERROR;
        }
        return AJAXResult.DELETE_SUCCESS;
    }
    @RequestMapping("/findAnnounce")
    @ResponseBody
    public AJAXResult findAnnounce(){
        List<Announce> aList=as.findAllAnnounce();
          return new AJAXResult(0,"",aList,new Long(5));

    }
}
